package com.gokzzz.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gokzzz.entity.Article;
import com.gokzzz.mapper.ArticleMapper;
import com.gokzzz.mq.config.RabbitMqConfig;
import com.gokzzz.mq.index.ArticleMqIndexMessage;
import com.gokzzz.response.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author gokzzz
 * @date 2022-05-22 21:24
 */

@Api(tags = "测试rabbitmq同步mysql数据到es")
@RestController
@RequestMapping("/rabbitmq")
@RequiredArgsConstructor
public class ArticleController {
    private final AmqpTemplate amqpTemplate;
    /**
     * 为了测试直接用mapper
     */
    private final ArticleMapper articleMapper;
    private final ObjectMapper objectMapper;

    @ApiOperation("添加文章")
    @PostMapping("/add")
    public Response add(@RequestBody Article article) throws JsonProcessingException {
        articleMapper.insert(article);
        amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE, RabbitMqConfig.ES_BIND_KEY,
                objectMapper.writeValueAsString(new ArticleMqIndexMessage(article.getId(),ArticleMqIndexMessage.CREATE)));
        return Response.success();
    }

    @ApiOperation("更新文章")
    @PutMapping("/update")
    public Response update(@RequestBody Article article) throws JsonProcessingException {
        articleMapper.updateById(article);
        amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE, RabbitMqConfig.ES_BIND_KEY,
                objectMapper.writeValueAsString(new ArticleMqIndexMessage(article.getId(),ArticleMqIndexMessage.UPDATE)));
        return Response.success();
    }

    @ApiOperation("删除文章")
    @DeleteMapping("/delete/{id}")
    public Response update(@PathVariable Long id) throws JsonProcessingException {
        articleMapper.deleteById(id);
        amqpTemplate.convertAndSend(RabbitMqConfig.ES_EXCHANGE, RabbitMqConfig.ES_BIND_KEY,
                objectMapper.writeValueAsString(new ArticleMqIndexMessage(id,ArticleMqIndexMessage.REMOVE)));
        return Response.success();
    }


}
